package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.VehicleListParam;
import com.ldkj.panzh.service.VehicleListService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.VehicleListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 车辆名单服务实现类（白名单/黑名单）
 *
 * @author qiancheng
 * @date 2025-11-19
 */
@Slf4j
@Service
public class VehicleListServiceImpl implements VehicleListService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    // 车辆白名单查询接口
    private static final String GET_WHITE_LIST_API = ARTEMIS_PATH + "/api/mpc/v1/alarm/white/search";
    // 车辆黑名单查询接口（通常与白名单API类似，可能是 /api/mpc/v1/alarm/black/search）
    private static final String GET_BLACK_LIST_API = ARTEMIS_PATH + "/api/mpc/v1/alarm/black/search";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    public CommentUtils commentUtils;

    /**
     * 查询车辆白名单
     */
    @Override
    public List<VehicleListVO> queryWhiteList(VehicleListParam vehicleListParam) throws Exception {
        return queryVehicleList(vehicleListParam, GET_WHITE_LIST_API, "白名单");
    }

    /**
     * 查询车辆黑名单
     */
    @Override
    public List<VehicleListVO> queryBlackList(VehicleListParam vehicleListParam) throws Exception {
        return queryVehicleList(vehicleListParam, GET_BLACK_LIST_API, "黑名单");
    }

    /**
     * 通用查询车辆名单方法
     */
    private List<VehicleListVO> queryVehicleList(VehicleListParam vehicleListParam, String apiUrl, String listName) throws Exception {
        
        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                vehicleListParam.getAppKey(),
                vehicleListParam.getAppSecret(),
                vehicleListParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put(PAGE_NO, vehicleListParam.getPageNo());
        paramMap.put(PAGE_SIZE, vehicleListParam.getPageSize());

        // 添加可选参数
        if (vehicleListParam.getPlateNo() != null && !vehicleListParam.getPlateNo().isEmpty()) {
            paramMap.put("plateNo", vehicleListParam.getPlateNo());
        }
        if (vehicleListParam.getPlateColor() != null) {
            paramMap.put("plateColor", vehicleListParam.getPlateColor());
        }
        if (vehicleListParam.getVehicleType() != null) {
            paramMap.put("vehicleType", vehicleListParam.getVehicleType());
        }
        if (vehicleListParam.getOwnerName() != null && !vehicleListParam.getOwnerName().isEmpty()) {
            paramMap.put("ownerName", vehicleListParam.getOwnerName());
        }
        if (vehicleListParam.getOwnerPhone() != null && !vehicleListParam.getOwnerPhone().isEmpty()) {
            paramMap.put("ownerPhone", vehicleListParam.getOwnerPhone());
        }
        if (vehicleListParam.getRegionIndexCodes() != null && !vehicleListParam.getRegionIndexCodes().isEmpty()) {
            paramMap.put("regionIndexCodes", vehicleListParam.getRegionIndexCodes());
        }
        if (vehicleListParam.getIsSubRegion() != null) {
            paramMap.put("isSubRegion", vehicleListParam.getIsSubRegion());
        }
        if (vehicleListParam.getStatus() != null) {
            paramMap.put("status", vehicleListParam.getStatus());
        }
        if (vehicleListParam.getStartTime() != null && !vehicleListParam.getStartTime().isEmpty()) {
            paramMap.put("startTime", vehicleListParam.getStartTime());
        }
        if (vehicleListParam.getEndTime() != null && !vehicleListParam.getEndTime().isEmpty()) {
            paramMap.put("endTime", vehicleListParam.getEndTime());
        }
        if (vehicleListParam.getOrderBy() != null && !vehicleListParam.getOrderBy().isEmpty()) {
            paramMap.put("orderBy", vehicleListParam.getOrderBy());
        }
        if (vehicleListParam.getOrderType() != null && !vehicleListParam.getOrderType().isEmpty()) {
            paramMap.put("orderType", vehicleListParam.getOrderType());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", apiUrl);
        List<VehicleListVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询车辆{}请求参数: {}", listName, body);

            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");

            log.info("查询车辆{}响应: {}", listName, response);

            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, VehicleListVO.class);
                        
                        // 填充枚举名称
                        fillEnumNames(resultList);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询车辆" + listName + "失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 填充枚举名称
     */
    private void fillEnumNames(List<VehicleListVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        for (VehicleListVO vo : list) {
            // 车牌颜色名称
            if (vo.getPlateColor() != null) {
                vo.setPlateColorName(getPlateColorName(vo.getPlateColor()));
            }
            
            // 车辆类型名称
            if (vo.getVehicleType() != null) {
                vo.setVehicleTypeName(getVehicleTypeName(vo.getVehicleType()));
            }
            
            // 名单类型名称
            if (vo.getListType() != null) {
                vo.setListTypeName(vo.getListType() == 0 ? "黑名单" : "白名单");
            }
            
            // 状态名称
            if (vo.getStatus() != null) {
                vo.setStatusName(vo.getStatus() == 0 ? "无效" : "有效");
            }
        }
    }

    /**
     * 获取车牌颜色名称
     */
    private String getPlateColorName(Integer plateColor) {
        switch (plateColor) {
            case 0: return "白色";
            case 1: return "黑色";
            case 2: return "蓝色";
            case 3: return "黄色";
            case 4: return "绿色";
            case 5: return "其他";
            default: return "未知";
        }
    }

    /**
     * 获取车辆类型名称
     */
    private String getVehicleTypeName(Integer vehicleType) {
        switch (vehicleType) {
            case 0: return "客车";
            case 1: return "货车";
            case 2: return "轿车";
            case 3: return "面包车";
            case 4: return "小型车";
            case 5: return "中型车";
            case 6: return "大型车";
            default: return "未知";
        }
    }

    /**
     * 查询白名单统计信息
     */
    @Override
    public Map<String, Object> queryWhiteListStats(VehicleListParam vehicleListParam) throws Exception {
        List<VehicleListVO> list = queryWhiteList(vehicleListParam);
        return calculateStats(list, "白名单");
    }

    /**
     * 查询黑名单统计信息
     */
    @Override
    public Map<String, Object> queryBlackListStats(VehicleListParam vehicleListParam) throws Exception {
        List<VehicleListVO> list = queryBlackList(vehicleListParam);
        return calculateStats(list, "黑名单");
    }

    /**
     * 计算统计信息
     */
    private Map<String, Object> calculateStats(List<VehicleListVO> list, String listName) {
        Map<String, Object> stats = new HashMap<>(8);
        
        if (list == null || list.isEmpty()) {
            stats.put("totalCount", 0);
            stats.put("validCount", 0);
            stats.put("invalidCount", 0);
            stats.put("plateColorStats", new HashMap<>());
            stats.put("vehicleTypeStats", new HashMap<>());
            return stats;
        }

        // 总数
        stats.put("totalCount", list.size());

        // 有效/无效统计
        long validCount = list.stream().filter(v -> v.getStatus() != null && v.getStatus() == 1).count();
        long invalidCount = list.stream().filter(v -> v.getStatus() != null && v.getStatus() == 0).count();
        stats.put("validCount", validCount);
        stats.put("invalidCount", invalidCount);

        // 车牌颜色统计
        Map<String, Long> plateColorStats = new HashMap<>();
        for (VehicleListVO vo : list) {
            if (vo.getPlateColorName() != null) {
                plateColorStats.merge(vo.getPlateColorName(), 1L, Long::sum);
            }
        }
        stats.put("plateColorStats", plateColorStats);

        // 车辆类型统计
        Map<String, Long> vehicleTypeStats = new HashMap<>();
        for (VehicleListVO vo : list) {
            if (vo.getVehicleTypeName() != null) {
                vehicleTypeStats.merge(vo.getVehicleTypeName(), 1L, Long::sum);
            }
        }
        stats.put("vehicleTypeStats", vehicleTypeStats);

        return stats;
    }
}
